//
//  JXLSportTracking.m
//  JXLSport
//
//  Created by 贾晓磊 on 16/10/24.
//  Copyright © 2016年 贾晓磊. All rights reserved.
//

#import "JXLSportTracking.h"

@implementation JXLSportTracking {
    //起始点位置
    CLLocation *_startLocation;
    // 所有运动线条模型的数组
    NSMutableArray<JXLSportTrackingLine *> *_trackingLines;
}

- (instancetype)initWithSportType:(JXLSportType )sportType sportState:(JXLSportState )sportState {
    if (self = [super init]) {
        _sportType = sportType;
        _sportState = sportState;
        _trackingLines = [NSMutableArray array];
    }
    return self;
}

- (JXLSportPolyLine *)appendLocation:(CLLocation *)location {
    
        // 0. 判断速度是否发生变化 - 性能优化，室内定位，速度有可能为`负数`
    if (location.speed <= 0) {
        return nil;
    }
    
    // 将定位时间和当前时间做比较，如果差值过大，说明 GPS 信号不好（室内／初始定位)
    // 目的：性能优化，减少不必要的数据点，减少杂线！
    CGFloat factor = 2;
    if ([[NSDate date] timeIntervalSinceDate:location.timestamp] >= factor) {
        return nil;
    }

    //1,判断起始点是否存在
    if (_startLocation == nil) {
        _startLocation = location;
        return nil;
    }
    
    // 3. 创建轨迹追踪线条模型
    JXLSportTrackingLine *trackingLine = [[JXLSportTrackingLine alloc] initWithStartLocation:_startLocation endLocation:location];
    //添加到数组
    [_trackingLines addObject:trackingLine];
    
    
    // 4. 将当前位置作为下一次起始位置
    _startLocation = location;
    
    // 5. 返回折线模型
    return trackingLine.polyLine;
}

- (void)setSportState:(JXLSportState)sportState {
    _sportState = sportState;
    
    // 判断状态类型，如果不是继续，需要清空起始点
    if (_sportState != JXLSportStateContinue) {
        _startLocation = nil;
    }
}

#pragma mark 计算型属性&公共方法
- (NSString *)totalTimeString {
    NSInteger totalTime = (NSInteger)self.totalTime;
    return [NSString stringWithFormat:@"%02zd:%02zd:%02zd",totalTime / 3600, (totalTime % 3600) / 60, totalTime % 60];
}

- (CLLocation *)sportStartLocation {
    // 返回运动轨迹线条数组中，第一个线条的起点
    return _trackingLines.firstObject.startLocation;
}

- (UIImage *)sportImage {
    UIImage *image;
    switch (_sportType) {
        case JXLSportTypeRun:
            image = [UIImage imageNamed:@"map_annotation_run"];
            break;
        case JXLSportTypeBike:
            image = [UIImage imageNamed:@"map_annotation_bike"];
            break;
        case JXLSportTypeWalk:
            image = [UIImage imageNamed:@"map_annotation_walk"];
            break;
    }
    return image;
}

- (double)avgSpeed {
    return [[_trackingLines valueForKeyPath:@"@avg.speed"] doubleValue];
}

- (double)maxSpeed {
    return [[_trackingLines valueForKeyPath:@"@max.speed"] doubleValue];
}

- (double)totalTime {
    return [[_trackingLines valueForKeyPath:@"@sum.time"] doubleValue];
}

- (double)totalDistance {
    return [[_trackingLines valueForKeyPath:@"@sum.distance"] doubleValue];
}


@end
